﻿using System.Text.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.EntityFrameworkCore;
using ConsoleApp1.Entitys;
using ConsoleApp1.Utility;
using Sample.ConsoleApp.CodeFist.Sqlite.TypeConverters;
using Sample.ConsoleApp.CodeFist.Sqlite.DbContexts;
using Sample.ConsoleApp.CodeFist.Sqlite.Repositories;

namespace Sample.ConsoleApp.CodeFist.Sqlite;

internal class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine("Hello, Microsoft.EntityFrameworkCore.Sqlite!");

        // 创建实体数据
        var entity = new MyEntity
        {
            RandomNo = Random.Shared.Next(0, 100),
            Data = JsonDocument.Parse("{\"name\":\"John\", \"age\":30}", JsonDocumentToStringConverter.GetJsonDocumentOptions()),
            CreatedTime = DateTime.Now
        };

        // 创建服务提供者
        var serviceProvider = ConfigureServices();

        {
            /*
            // 1.常规模式
            // 获取服务实例
            //using var context = serviceProvider.GetService<MyDb1Context>();
            using var context = serviceProvider.GetService<MyDb2Context>();

            // 使用服务
            // 新增数据
            context?.MyEntitys.Add(entity);
            context?.SaveChanges();

            // 读取数据
            var savedEntity = context?.MyEntitys.FirstOrDefault(e => e.Id == entity.Id);
            var name = savedEntity?.Data.RootElement.GetProperty("name").GetString();
            Console.WriteLine(name); // 输出 "John"
            */
        }

        {
            // 2.仓储模式
            // 获取服务实例
            var repository = serviceProvider.GetService<IMyEntityRepository>();

            if (repository != null)
            {
                // 使用服务，新增数据
                var id = await repository!.AddAsync(entity);

                // 读取数据
                var savedEntity = await repository!.GetAsync(id);
                var name = savedEntity?.Data.RootElement.GetProperty("name").GetString();
                Console.WriteLine(name); // 输出 "John"
            }
        }
    }

    /// <summary>
    /// 注册服务
    /// </summary>
    /// <returns></returns>
    private static ServiceProvider ConfigureServices()
    {
        // 创建服务容器
        var serviceCollection = new ServiceCollection();

        #region 添加 EF Core DbContext
        serviceCollection.AddDbContext<MyDb1Context>();

        var directoryHelper = new DirectoryHelper();
        string connectionString = directoryHelper.GetSqliteConnectionString();
        serviceCollection.AddDbContextFactory<MyDb2Context>(options => options.UseSqlite(connectionString));
        #endregion

        // 注入 MyDb1Context 仓储模式
        serviceCollection.AddScoped<IMyEntityRepository, MyEntityRepository>();

        // 构建服务提供者
        return serviceCollection.BuildServiceProvider();
    }
}
